// pages/search/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchlist:[], //页面渲染的数据
    iptvalue:"", //搜索框绑定的值
    historylist:[
      "小米","华为"
    ]//历史记录
  },

    /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let historylist = wx.getStorageSync('histroy') || []
    this.setData({
      historylist
    })
  },
  
  //防抖节流定时器
  timeout:1,

  //搜索
  searchipt:function(e){
    clearTimeout(this.timeout)
    console.log(e);
     //ipt中的值
     let {value} = e.detail
     value = value.trim()
     console.log(value);
     
     //校验
     if(!value){
      clearTimeout(this.timeout)
      this.setData({
        searchlist:[]
      })
       return;
     }
     


     this.timeout = setTimeout(()=>{
      this.goodqsearch(value)
     },2000)
  },

  //发送请求
  goodqsearch: async function (queryvalue) {
    let {historylist} =this.data 
    let index = historylist.findIndex(item=>item === queryvalue)
    if(index === -1){
      historylist.push(queryvalue)
    }


    let {data} = await wx.gooddetailApi.goodqsearch({query:queryvalue})
    console.log('data',data);
    this.setData({//页面数据赋值
      searchlist:data.message,
      historylist//历史记录
    })
    console.log(this.data.searchlist);

    wx.setStorageSync('histroy', historylist)
  },

  //取消
  calloff:function(){
    this.setData({
      searchlist:[],
      iptvalue:''
    })
  },
  
  //清空历史记录
  clearhistroy:function(){
    this.setData({
      historylist:[]
    })
    wx.setStorageSync('histroy', [])
  },

  //点击记录搜索
  cliclitem:function(e){
    console.log('lsitem',e);
    let {item} = e.currentTarget.dataset
    this.goodqsearch(item)
    this.setData({
      iptvalue:item
    })
  }




})